package cn.caplike.demo.rabbitmq.api.message;

import cn.caplike.demo.rabbitmq.api.Application;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 发送一个带有附加属性的消息
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-18 14:43
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建一个链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Application.RABBITMQ_HOST);
        connectionFactory.setPort(Application.RABBITMQ_PORT);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        Channel channel = connection.createChannel();

        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("key1", "val1");
        headerMap.put("key2", "val2");
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties.Builder()
                // 2 持久化消息: 这个消息发到服务器上, 如果服务器重启, 消息依然存在
                .deliveryMode(2)
                .contentEncoding("UTF-8")
                // 15s 过期
                .expiration("15000")
                .headers(headerMap)
                .build();

        // 通过 Channel 发送数据
        for (int idx = 0; idx < 5; idx++) {
            channel.basicPublish("", "test002", basicProperties, "Hello RabbitMQ!".getBytes());
        }

        // 关闭连接
        channel.close();
        connection.close();
    }

}
